package com.example.fw;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

import static org.testng.Assert.fail;

/**
 * Created with IntelliJ IDEA.
 * User: raimbek
 * Date: 07.03.13
 * Time: 0:38
 */
public class ApplicationManager {
    private WebDriver driver;
    public String baseUrl;
    private StringBuffer verificationErrors = new StringBuffer();

    private Properties properties;
    private HibernateHelper hibernateHelper;
    private AccountHelper accountHelper;
    private MailHelper mailHelper;
    private JamesHelper jamesHelper;


    public ApplicationManager(Properties properties) {
        this.properties = properties;
    }

    public WebDriver getDriver() {
        if (driver == null) {
            String browser = properties.getProperty("browser");
            if (browser.equals("firefox")) {
                driver = new FirefoxDriver();
            } else if (browser.equals("ie")) {
                driver = new InternetExplorerDriver();
            } else if (browser.equals("chrome")) {
                driver = new ChromeDriver();
            } else {
                throw new Error("Unsupported browser: " + browser);
            }

            baseUrl = properties.getProperty("baseUrl");
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
            driver.get(baseUrl);
        }
        return driver;
    }

    public void stop() {
        driver.quit();
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }

    public HibernateHelper getHibernateHelper() {
        if (hibernateHelper == null) {
            hibernateHelper = new HibernateHelper(this);
        }
        return hibernateHelper;
    }

    public String getPropertyKey(String key) {
        return properties.getProperty(key);
    }

    public AccountHelper getAccountHelper() {
        if (accountHelper == null) {
            accountHelper = new AccountHelper(this);
        }
        return accountHelper;
    }

    public MailHelper getMailHelper() {
        if (mailHelper == null) {
            mailHelper = new MailHelper(this);
        }
        return mailHelper;
    }

    public JamesHelper getJamesHelper() {
        if (jamesHelper == null) {
            jamesHelper = new JamesHelper(this);
        }
        return jamesHelper;
    }
}